package Master;

import Module.RegistryService;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by IntelliJ IDEA.
 * User: lihengfeng
 * Date: 11-5-19
 * Time:
 * To change this template use File | Settings | File Templates.
 */
public class RegistryInfo {

    public static boolean AuthSecutiry(Resource resource) {
        boolean result = false;
        try {

            RegistryService registryService = resource.getRegistryService();

            String ciphertext = Md5Encryption(resource.getPassword());

            System.out.println("master engine ciphertext: " + ciphertext);
            if(registryService == null){
                System.out.println("Registry service NULL!!!!");
            }

            String authCode = registryService.authenticate(ciphertext);

            System.out.println("auth code: " + authCode);

            if(authCode == null)
            {
                result = false;
            }
            else {
                result = true;

                resource.setAuthCode(authCode);
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return result;
    }

    private static String Md5Encryption(String plainText ) {
        String ciphertext = "";
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(plainText.getBytes());

            byte b[] = md5.digest();
            int i;

            StringBuffer buffer = new StringBuffer("");
            for(int element : b) {
                i = element;
                if( i < 0) {
                    i += 256;
                }
                if( i < 16){
                    buffer.append("0");
                }
                buffer.append(Integer.toHexString(i));
            }

            // 32 bit code
            //System.out.println("result: " + buffer.toString());

            // 16 bits code
            //System.out.println("result: " + buffer.toString().substring(8,24));

            ciphertext = buffer.toString().substring(8,24);

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();
        }
        return ciphertext;
    }
}
